<template>
  <div id="demand_add">
    <div class="top">
      <van-nav-bar
        title="发起需求收集"
        left-arrow
        @click-left="$router.push('/demand')"
      />
    </div>

    <div class="download">
      <a :href="`${baseurl}/report/auto?access_token=${access_token}&modelId=2`"
        >需求模板下载</a
      >
    </div>
    <div
      class="add"
      v-for="(item, index) in form"
      :key="index"
      @click.capture="clickItem(index)"
    >
      <van-form
        label-width="auto"
        :colon="true"
        scroll-to-error
        input-align="right"
        label-align="left"
        ref="form"
      >
        <van-field
          class="mandatory"
          v-model="item.title"
          name="需求标题"
          label="需求标题"
          placeholder="请填写"
          :rules="[{ required: true, message: '' }]"
        />
        <van-field
          class="mandatory"
          v-model="item.submitter"
          name="需求提交人"
          label="需求提交人"
          placeholder="请填写"
          :rules="[{ required: true, message: '' }]"
        />
        <!-- <van-field
          class="mandatory"
          v-model="item.unit"
          name="需求方单位"
          label="需求方单位"
          placeholder="请填写"
          :rules="[{ required: true, message: '' }]"
        /> -->
        <!-- 需求单位 -->
        <van-field        
        class="mandatory"    
                v-model="item.unit"
                name="需求方单位"
                label="需求方单位"
                clickable
                placeholder="输入/选择需求方单位"
                right-icon="arrow"
                @click-right-icon="demandForTheUnit = true"
            />
        <van-popup v-model="demandForTheUnit" position="bottom">
            <van-picker
                show-toolbar
                :columns="demandForUnit"
                value-key="name"
                @confirm="demandUnit"
                @cancel="demandForTheUnit = false"
            />
        </van-popup>

        <van-field
          class="mandatory"
          v-model="item.commitPhone"
          name="提交人电话"
          label="提交人电话"
          placeholder="请填写"
          :rules="[
            {
              validator: (val) =>
                val
                  ? /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
                      val
                    )
                  : true,
              message: '请输入正确的电话号码',
            },
            { required: true, message: '' },
          ]"
        />
        <van-field
          class="mandatory"
          v-model="item.background"
          name="需求背景"
          label="需求背景"
          placeholder="请填写"
          :rules="[{ required: true, message: '' }]"
        />
        <!-- <van-field
                    v-model="item.sourceDemand"
                    name="需求源头"
                    label="需求源头"
                    placeholder="请填写"
                /> -->
        <van-field
          class="mandatory"
          v-model="item.content"
          name="需求内容描述"
          label="需求内容描述"
          placeholder="请填写"
          :rules="[{ required: true, message: '' }]"
        />
        <van-field
          class="mandatory"
          :value="item.classification_level.name"
          name="需求分类一级"
          label="需求分类一级"
          readonly
          clickable
          placeholder="请选择"
          @click="showLevel = true"
          right-icon="arrow"
          :rules="[{ required: true, message: '' }]"
        />

        <van-field
          class="mandatory"
          :value="item.classification_second_level.name"
          name="需求分类二级"
          label="需求分类二级"
          readonly
          clickable
          placeholder="请选择"
          right-icon="arrow"
          :rules="[{ required: true, message: '' }]"
          @click="showSecondLevelList"
        />
        <van-field
          class="mandatory"
          label="需求期望实现日期"
          readonly
          clickable
          name="calendar"
          :value="item.demandImplementTime"
          :rules="[{ required: true, message: '' }]"
          placeholder="请选择"
          right-icon="arrow"
          @click="showCalendar = true"
        />

        <van-field name="uploader" label="需求附件" placeholder="请选择">
          <template #input>
            <van-uploader
              accept=""
              multiple
              v-model="item.attachment"
              upload-text="请选择"
            >
              <van-icon color="#333" name="arrow" />
            </van-uploader>
          </template>
        </van-field>

        <div
          class="delete"
          @click="deleDemand(index)"
          v-show="index != form.length - 1"
        >
          <van-icon name="delete-o" />删除
        </div>
        <div
          v-show="index == form.length - 1"
          class="addDemand"
          @click="addDemand"
        >
          <van-icon name="plus" />新增需求
        </div>
      </van-form>
    </div>
    <van-calendar v-model="showCalendar" @confirm="dateConfirm" />
    <van-popup v-model="showLevel" position="bottom">
      <van-picker
        show-toolbar
        :columns="classification_level"
        @confirm="levelConfirm"
        @cancel="showLevel = false"
      >
        <template #option="option">
          <div
            style="display: flex; flex-direction: column; align-items: center"
          >
            <div>{{ option.name }}</div>
          </div>
        </template>
      </van-picker>
    </van-popup>
    <van-popup v-model="showSecondLevel" position="bottom">
      <van-picker
        show-toolbar
        :columns="classification_second_level"
        @confirm="secondLevelConfirm"
        @cancel="showSecondLevel = false"
      >
        <template #option="option">
          <div
            style="display: flex; flex-direction: column; align-items: center"
          >
            <div>{{ option.name }}</div>
          </div>
        </template></van-picker
      >
    </van-popup>

    <div class="submit">
      <van-button
        round
        block
        type="info"
        @click="onSubmit"
        :loading="loading"
        :disabled="loading"
        >提交</van-button
      >
    </div>
  </div>
</template>
<script>
import { Toast } from "vant";
import api from "../../http/api";
import { BASEURL, ACCESS_TOKEN } from "../../http/apiUrl";
export default {
  data() {
    return {
      //   count: 0,
      loading: false,
      // 当前操作表单
      curIndex: 0,
      // 文件列表
      fileList: [],
      baseurl: null,
      access_token: null,
      formData: null,
      // 需求表单
      form: [
        {
          title: "",
          submitter: "",
          unit: "",
          background: "",
          content: "",
          classification_level: "",
          classification_second_level: "",
          attachment: [],
          sourceDemand: "",
          demandImplementTime: "",
          commitPhone: "",
        },
      ],
      demandForTheUnit:false,
      demandForUnit:[],
      // 需求一级分类
      showLevel: false,

      classification_level: [
        {
          id: "XQFL-GTYJ",
          name: "钢铁冶金",
          child: [
            {
              id: "GTYJ-MHG",
              name: "煤化工",
            },
            {
              id: "LTLGJNC-LG",
              name: "炼铁炼钢及耐材(炼钢)",
            },
            {
              id: "LTLGJNC-PG",
              name: "炼铁炼钢及耐材(普钢炼钢)",
            },
            {
              id: "LTLGJNC-TG",
              name: "炼铁炼钢及耐材(特钢炼钢)",
            },
          ],
        },
        {
          id: "XQFL-JSCLJJG",
          name: "金属材料及加工",
          child: [
            {
              id: "GTCL-ZG",
              name: "钢铁材料(重轨和型材产品)",
            },
            {
              id: "GTCL-PGCP",
              name: "钢铁材料(普钢板材产品)",
            },
            {
              id: "GTCL-TG",
              name: "钢铁材料(特钢)",
            },
            {
              id: "YLJG-PG",
              name: "压力加工(普钢)",
            },
            {
              id: "YLJG-TG",
              name: "压力加工(特钢)",
            },
          ],
        },
        {
          id: "XQFL-FZY",
          name: "钒专业",
          child: [
            {
              id: "FHG-CFDC",
              name: "钒化工(除钒电池外)",
            },
            {
              id: "FHG-FDC",
              name: "钒化工(钒电池)",
            },
            {
              id: "FYJ",
              name: "钒冶金",
            },
          ],
        },
        {
          id: "XQFL-TZY",
          name: "钛专业",
          child: [
            {
              id: "THG",
              name: "钛化工",
            },
            {
              id: "TYJ-HMT",
              name: "钛冶金(海绵钛)",
            },
            {
              id: "TCL-BC",
              name: "钛材料(板材)",
            },
            {
              id: "TYJ-TRL",
              name: "钛冶金(钛熔炼)",
            },
            {
              id: "TCL-XC",
              name: "钛材料(型材等)",
            },
          ],
        },
        {
          id: "XQFL-KSGC",
          name: "矿山工程",
          child: [
            {
              id: "KGGC-CK",
              name: "采矿",
            },
            {
              id: "KGGC-XK",
              name: "选矿",
            },
            {
              id: "KGGC-DZ",
              name: "地质",
            },
          ],
        },
        {
          id: "XQFL-JNHB",
          name: "节能环保",
          child: [
            {
              id: "JNHB-HB",
              name: "环保",
            },
            {
              id: "JNHB-NYDL",
              name: "能源动力",
            },
          ],
        },
        {
          id: "XQFL-JXJYY",
          name: "机械及液压",
          child: [
            {
              id: "JXJYY-YY",
              name: "液压",
            },
            {
              id: "JXJYY-JX",
              name: "机械",
            },
          ],
        },
        {
          id: "XQFL-ZDHJXXH",
          name: "自动化及信息化",
          child: [
            {
              id: "ZDHJXXH-DQ",
              name: "电气",
            },
            {
              id: "ZDHJXXH-ZK",
              name: "自控",
            },
            {
              id: "ZDHJXXH-XXH",
              name: "信息化",
            },
          ],
        },
      ],
      // 需求二级分类
      showSecondLevel: false,
      classification_second_level: [],
      // 需求期望实现日期
      showCalendar: false,
      //   data: null,
    };
  },
  mounted() {
    this.baseurl = BASEURL;
    this.access_token = ACCESS_TOKEN;
    // api.demand.getDemandUnit().then((res)=>{     
    //     for(var i = 0;i<res.data.data.length;i++){
    //         res.data.data[i].id = i
    //         res.data.data[i].name = res.data.data[i].demandName
    //     }
    //     this.demandForUnit.push(...res.data.data)
    //     console.log('this.demandForUnit :>> ', this.demandForUnit);

    // })
  },
  // watch: {
  //     count(val) {
  //         if (val == this.form.length) {
  //             console.log("执行完成");
  //             api.demand
  //                 .addDemand({ loginPhone: localStorage.phone, data:this.data })
  //                 .then((res) => {
  //                     console.log(res);
  //                     this.loading = false;
  //                     if (res.data.code == 200) {
  //                         Toast.success("提交成功");
  //                         setTimeout(() => {
  //                             this.$router.push("/demand");
  //                         }, 800);
  //                     } else {
  //                         Toast.fail("提交失败");
  //                     }
  //                 });
  //         }
  //     },
  // },
  methods: {
    clickItem(index) {
      this.curIndex = index;
    },
    // 需求模板下载
    download() {
      window.location.href = `https://592r24087e.goho.co/report/auto?access_token=030f4470-0e71-4d23-bb74-644afb24190e&modelId=1`;
    },
    showSecondLevelList() {
      if (this.form[this.curIndex].classification_level.name) {
        this.showSecondLevel = true;
      } else {
        Toast.fail("请选择需求一级分类");
      }
    },
    // 提交
    async onSubmit(values) {
      const errorArr = [];
      for (let i = 0; i < this.form.length; i++) {
        await this.$refs.form[i].validate().catch((info) => {
          errorArr.push(info);
        });
      }
      if (errorArr.length != 0) return;
      this.loading = true;
      const data = this.form.map((item) =>
        Object.fromEntries(Object.entries(item))
      );

      for (let i = 0; i < data.length; i++) {
        data[i] = await this.upload(data[i]);
      }
        console.log("data >> :",data);
        await setTimeout(() => {
        api.demand
          .addDemand({ loginPhone: localStorage.phone/*15181798337*/, data: data })
          .then((res) => {
            console.log(res);
            this.loading = false;
            if (res.data.code == 200) {
              Toast.success("提交成功");
              setTimeout(() => {
                this.$router.push("/demand");
              }, 800);
            } else {
              Toast.fail("提交失败");
            }
          });
      });
    },
    async upload(item) {
      if (item.attachment.length > 0) {
        let formData = new FormData();
        item.attachment.forEach((item) => {
          formData.append("file", item.file);
        });
        const resp = await api.file.upload(formData);
        console.log("文件上传", resp);
        // if (resp.data.code == 200) {
        item.attachment = resp.data.data;
        // this.count++;
        // }
      } else {
        item.attachment = [{}];
        // this.count = this.data.length;
      }
      item.classification_second_level = item.classification_second_level.id;
      item.classification_level = item.classification_level.id;
      return item;
    },
    // 选择需求单位
    demandUnit(val) {
      this.form[this.curIndex].unit = val.name;
      this.demandForTheUnit = false;
    },
    // 选择需求分类一级
    levelConfirm(val) {
      this.form[this.curIndex].classification_level = val;
      this.classification_second_level = val.child;
      this.showLevel = false;
    },
    // 选择需求分类二级
    secondLevelConfirm(val) {
      this.form[this.curIndex].classification_second_level = val;
      this.showSecondLevel = false;
    },
    // 需求期望实现日期
    dateConfirm(date) {
      this.form[this.curIndex].demandImplementTime = `${date.getFullYear()}-${
        date.getMonth() + 1
      }-${date.getDate()}`;
      this.showCalendar = false;
    },
    /**
     * 新建一个需求表单
     */
    addDemand() {
      var item = () => ({
        title: "",
        submitter: "",
        unit: "",
        background: "",
        content: "",
        classification_level: "",
        classification_second_level: "",
        attachment: [],
        demandImplementTime: "",
        commitPhone: "",
        sourceDemand: "",
      });
      this.form.push(item());
    },
    deleDemand(index) {
      this.form.splice(index, 1);
    },
  },
};
</script>

<style lang="less" scoped>
#demand_add {
  width: 100vw;
  min-height: calc(100vh - 64px);
  background-color: #f5f5f5;
  padding-bottom: 64px;
  padding-top: 51px;
  box-sizing: border-box;
  .top {
    position: fixed;
    width: 100%;
    top: 0;
    overflow: hidden;
    background-color: white;
    z-index: 1;
  }
  .download {
    position: fixed;
    right: 10px;
    top: 13px;
    background: rgba(14, 134, 209, 0.2);
    border: 1px solid #0e86d1;
    border-radius: 5px;
    font-family: "ABeeZee";
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 23px;
    padding: 0 4px;
    text-align: center;
    letter-spacing: -0.24px;

    z-index: 1;
    a {
      color: #0e86d1;
    }
  }
  .add {
    margin: 10px;
  }
  .delete {
    width: 100%;
    display: flex;
    justify-content: center;
    color: red;
    height: 44px;
    line-height: 44px;
    align-items: center;
    font-size: 0.3733rem;
    vertical-align: middle;
    background-color: white;
    /deep/ .van-icon {
      height: max-content;
    }
  }
  .addDemand {
    width: 100%;
    display: flex;
    justify-content: center;
    color: #0e86d1;
    height: 44px;
    line-height: 44px;
    align-items: center;
    font-size: 0.3733rem;
    vertical-align: middle;
    background-color: white;
    /deep/ .van-icon {
      height: max-content;
    }
  }
  .van-form {
    /deep/ .van-cell {
      align-items: center;
    }
    /deep/ .van-checkbox--horizontal {
      padding: 10px;
      margin: 0;
    }
    /deep/ .van-radio--horizontal {
      overflow: visible;
    }
    /deep/ .van-field__error-message {
      text-align: right !important;
    }
    .mandatory {
      position: relative;
      &::after {
        content: "*";
        display: block;
        position: absolute;
        left: 5px;
        top: 14px;
        font-size: 16px;
        color: red;
        transform: scale(1);
      }
    }
  }
  .submit {
    padding: 10px;
    width: 100%;
    position: fixed;
    bottom: 0;
    height: 64px;
    box-sizing: border-box;
    background-color: white;
    /deep/ .van-button--block {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      padding: 10px 143.5px;
      gap: 10px;
      background: #0e86d1;
      border-radius: 4px;
    }
  }
}
/deep/ .van-ellipsis {
  overflow: visible;
}
/deep/ .van-nav-bar__left {
  padding: 10px;
}
/deep/ .van-ellipsis {
  overflow: visible;
}
/deep/ .van-nav-bar__content {
  height: 51px;
}
/deep/ .van-nav-bar__title {
  font-family: "Inter";
  font-style: normal;
  font-weight: 600;
  font-size: 18px;
  line-height: 20px;
  /* identical to box height, or 111% */

  text-align: center;
  letter-spacing: -0.24px;

  color: #333333;
}
/deep/ .van-nav-bar .van-icon {
  /* 文字颜色3 */

  color: #999999;
}
/deep/ .van-field__control::-webkit-input-placeholder {
  text-align: right;
}
/deep/ .van-uploader__file-name {
  overflow: hidden;
  text-align: right;
}
/deep/ .van-uploader__input-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
/deep/ .van-uploader__file-icon {
  display: none;
}
/deep/ .van-uploader__file {
  width: auto;
  height: auto;
  background-color: transparent;
}
/deep/ .van-field__value {
  overflow: hidden;
}
/deep/ .van-uploader__preview,
/deep/ .van-uploader,
/deep/ .van-uploader__input-wrapper {
  width: 100%;
}
/deep/ .van-uploader__preview {
  margin: 0;
}
</style>
